package wechat

import (
	"alertmanager-webhook/model"
	"alertmanager-webhook/transformer"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

func SendWechat(notification model.Notification, webhook string) (err error) {
	//把告警转换为markdown格式
	markdown, err := transformer.TransformWechatMarkdown(notification)
	if err != nil {
		return
	}
	//将消息结构体编码为json字符串
	data, err := json.Marshal(markdown)
	if err != nil {
		return
	}

	//创建请求体
	reqBody := bytes.NewBuffer(data)

	//创建http请求
	client := &http.Client{}
	req, err := http.NewRequest("POST", webhook, reqBody)
	if err != nil {
		return err
	}
	//添加请求头
	req.Header.Set("Content-Type", "application/json")
	//发送请求
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	//读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return
	}
	log.Println(string(body))
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("发送失败，状态码：%d", resp.StatusCode)
	}
	return nil
}
